package com.lvcoding.auth2.auth.shizhan.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义认证异常类
 * <p>
 * 通常是请求了需要认证的资源，但是没有认证成功，会触发认证异常
 * 返回401
 *
 * @author wuyanshen
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("msg", authException.getMessage());
        String jsonStr = objectMapper.writeValueAsString(map);
        response.setContentType("application/json;charset=utf8");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(jsonStr.getBytes());
        // PrintWriter writer = response.getWriter();
        // writer.write(jsonStr);
        // writer.flush();
        // writer.close();
        return;
    }
}
